package learn.dwr.reverse;  
  
import java.util.Date;  
import java.util.concurrent.ScheduledThreadPoolExecutor;  
import java.util.concurrent.TimeUnit;  
import org.directwebremoting.Browser;  
import org.directwebremoting.ServerContextFactory;  
import org.directwebremoting.ui.dwr.Util;  
  
/** 
 * title: 时钟 
 *  
 * @author Administrator 
 * @时间 2009-11-21:下午07:11:56 
 */  
public class MyClock implements Runnable {  
    // 这个active必需用static，使用transient标识是无法使用哦。  
    protected static boolean active = false;  
  
    public MyClock() {  
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(  
                1);  
        executor.scheduleAtFixedRate(this, 1, 1, TimeUnit.SECONDS);  
    }  
  
    public void run() {  
        if (active) {  
            setClockDisplay((new Date()).toString());  
        }  
    }  
  
    public synchronized void toggle() {  
        active = !active;  
        if (active) {  
            setClockDisplay("Started");  
        } else {  
  
            setClockDisplay("Stopped");  
        }  
    }  
  
    public void setClockDisplay(final String output) {  
        String page = ServerContextFactory.get().getContextPath()  
                + "/reverseajax/clock.html";  
        System.out.println(page + "  " + output);  
        Browser.withPage(page, new Runnable() {  
            public void run() {  
                Util.setValue("clockDisplay", output);  
            }  
        });  
  
    }  
}  